<template>
  <div>
    <Navbar />
    <SearchTitle :count="totalItems" />
    <div class="content-container">
      <n-grid :cols="4" x-gap="12" y-gap="12">
        <n-grid-item v-for="api in apis" :key="api.id">
          <ApiCard
            :id="api.id"
            imageSrc="https://cdn.free-api.com/tqybjh.webp"
            :name="api.name"
            :description="api.description"
            :visitedCount="api.visitedCount"
            :interfaceLabelList="api.interfaceLabelList"
            :uploadTime="api.createTime"
          />
        </n-grid-item>
      </n-grid>
    </div>
    <div class="pagination-container">
      <n-pagination
        v-if="totalItems > 0"
        :page="currentPage"
        :page-size="pageSize"
        :page-count="pageCount"
        show-size-picker
        show-quick-jumper
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
      />
    </div>
    <Footer />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed, watch } from 'vue'
import { useRoute } from 'vue-router'
import Navbar from '@/components/Navbar.vue'
import SearchTitle from '@/components/interface/SearchTitle.vue'
import ApiCard from '@/components/interface/ApiCard.vue'
import Footer from '@/components/Footer.vue'
import apiClient from '@/api/axios.ts'

// 定义响应式变量
const apis = reactive([])
const totalItems = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const route = useRoute()
const keyword = computed(() => route.query.keyword || '')

const fetchApis = async () => {
  try {
    const response = await apiClient.post('/interfaceInfo/list/page', {
      name: keyword.value,
      pageSize: pageSize.value,
      current: currentPage.value,
      status: 0
    });
    const responseData = response.data;
    if (responseData.code === 0) {
      console.log('查询到的接口信息:', responseData);
      // 更新响应式变量
      apis.splice(0, apis.length, ...responseData.data.records);
      totalItems.value = responseData.data.total;
    } else {
      console.error('查询接口信息列表失败，返回的状态码:', responseData.code);
    }
  } catch (error) {
    console.error('查询接口信息列表失败:', error);
  }
};

// 计算总页数
const pageCount = computed(() => {
  return Math.ceil(totalItems.value / pageSize.value);
});

// 处理分页变化
const handlePageChange = (page) => {
  currentPage.value = page;
  fetchApis();
}

// 处理页面大小变化
const handlePageSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
  fetchApis();
}

// 监听路由变化
watch(route, fetchApis, { immediate: true });

onMounted(fetchApis)
</script>

<style scoped>
.content-container {
  margin: 20px;
}

.pagination-container {
  margin: 20px;
  display: flex;
  justify-content: center;
}
</style>
